package com.zhaosc.parse;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.BeanDefinitionParser;
import org.springframework.beans.factory.xml.ParserContext;
import org.w3c.dom.Element;

public class ProtocolBeanDefinitionParser implements BeanDefinitionParser {
	/*
	 * <xsd:attribute name="name" type="xsd:string"></xsd:attribute>
	 * <xsd:attribute name="port" type="xsd:string"></xsd:attribute>
	 * <xsd:attribute name="host" type="xsd:string"></xsd:attribute>
	 */
	private Class<?> beanClass;

	public ProtocolBeanDefinitionParser(Class<?> beanClass) {
		this.beanClass = beanClass;
	}

	@Override
	public BeanDefinition parse(Element element, ParserContext parserContext) {

		String name = element.getAttribute("name");
		String port = element.getAttribute("port");
		String host = element.getAttribute("host");

		if (name == null || "".equals(name)) {
	           throw new RuntimeException("Protocol name 不能为空！");
		}
		if (port == null || "".equals(port)) {
	           throw new RuntimeException("Protocol port 不能为空！");
		}
		if (host == null || "".equals(host)) {
	           throw new RuntimeException("Protocol host 不能为空！");
		}
		
		RootBeanDefinition beanDefinition=new RootBeanDefinition();
		beanDefinition.setLazyInit(false);
		beanDefinition.setBeanClass(beanClass);
		beanDefinition.getPropertyValues().add("name", name);
		beanDefinition.getPropertyValues().add("port", port);
		beanDefinition.getPropertyValues().add("host", host);
		//注册
		parserContext.getRegistry().registerBeanDefinition("protocol"+host+port, beanDefinition);
		return beanDefinition;
	}

}
